<?php

namespace App\Http\Api\Controllers\Order;

use App\Exceptions\InvalidRequestException;

use App\Http\Api\Services\FxgService;
use App\Http\Controllers\Controller;
use App\Http\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use UpdateHelper\NotUpdateInterfaceInstanceException;


class FxgOrderApiController extends Controller
{
    protected $fxgService;

    public function __construct(FxgService $fxgService)
    {
        $this->fxgService = $fxgService;
    }

    public function updateOrder(Request $request)
    {
        set_time_limit(0);
        $start_time = $request->input('start_time') ?? date("Y-m-d", strtotime("-2 day")) . ' 00:00:00';
        $end_time = $request->input('end_time') ?? date("Y-m-d H:i:s");
        $flag = $request->input('flag') ?? '';
        $order_status = $request->input('order_status') ?? '';

        $data = $this->recvData($start_time, $end_time, $order_status);

        $arr = [];
        foreach ($data as $k => $v) {
            foreach ($v as $kk => $vv) {
                array_push($arr, $vv);
            }

        }

        return res('采集完成', count($arr));

    }


    /*
     * Api获取订单数据
     */
    public function recvData($start_time, $end_time, $order_status)
    {


        //店铺信息
        //$shop = $this->getShop();

        $shop   =   array([
            "appKey"=>"6970974314099131935",
            "appSecret"=>"81666580-db8c-470a-982b-85b94b819f71"
        ]);



        $send_arr = [];
        $count = 0;
        foreach ($shop as $k => $v) {
            if (!empty($v['appKey']) && !empty($v['appSecret'])) {

                $attributes['APP_KEY'] = $v['appKey'];
                $attributes['APP_SECRET'] = $v['appSecret'];
                $attributes['timestamp'] = $end_time;
                $attributes['access_token'] = "4665c82d-bb45-4a22-a2a2-20c8001e7113";
                $attributes['c'] = 'order';
                $attributes['a'] = 'searchList';
                if(!empty($order_status)){
                    $attributes['param_arr'] = array(
                        "create_time_start" => $start_time,
                        "create_time_end" => $end_time,
                        "order_status"=>$order_status,
                        "is_desc" => '1',
                        "size" => "100",
                        "page" => "0",
                    );
                }else{
                    $attributes['param_arr'] = array(
                        "create_time_start" => strtotime($start_time),
                        "create_time_end" => strtotime($end_time),
                        "is_desc" => '1',
                        "size" => "100",
                        "page" => "0",
                    );
                }



                $order_data = $this->fxgService->sendFxgRequest($attributes);

				dd($order_data);
//                if (!empty($order_data)) {
//                    $all_page = ceil($order_data['data']['total'] / 100);
//
//                    //更新第一页数据
//                    if (!empty($order_data['data']['list'])) {
//                        $list_data = $this->putOrder($order_data['data']['list'], $v['shop_name']);
//                        array_push($send_arr, $list_data);
//                    }
//
//                    if ($all_page > 1) { //判断总页数是否少于 1
//
//                        for ($i = 1; $i < $all_page; $i++) {    //从第二页开始更新
//                            $attributes['param_arr'] = array(
//                                "start_time" => $start_time,
//                                "end_time" => $end_time,
//                                "is_desc" => '1',
//                                "size" => "100",
//                                "page" => "$i",
//                            );
//                            $order_data = $this->fxgService->sendFxgRequest($attributes);
//                            if (!empty($order_data['data']['list'])) {
//                                $list_data = $this->putOrder($order_data['data']['list'], $v['shop_name']);
//                                array_push($send_arr, $list_data);
//                            }
//
//                        }
//                    }
 //               }


            }
        }

        return $send_arr;
    }

    /*
     *同步 时间-店铺 数据
     */

    public function updaShopTimeOrder(Request $request)
    {
        set_time_limit(500);
        $start_time = $request->input('start_time') ?? '';
        $end_time = $request->input('end_time') ?? '';
        $app_key = $request->input('app_key') ?? '';
        $app_secret = $request->input('app_secret') ?? '';
        $page = $request->input('page') ?? '0';
        $shop_name = $request->input('shop_name') ?? '';

        $result = [];
        if (!empty($start_time) && !empty($end_time)) {

            $attributes['APP_KEY'] = $app_key;
            $attributes['APP_SECRET'] = $app_secret;
            $attributes['timestamp'] = $end_time;
            $attributes['c'] = 'order';
            $attributes['a'] = 'list';
            $attributes['param_arr'] = array(
                "start_time" => $start_time,
                "end_time" => $end_time,
                "is_desc" => '1',
                "size" => "100",
                "page" => "$page",
            );


            $order_data = $this->fxgService->sendFxgRequest($attributes);


            if (!empty($order_data)) {
                $result['total'] = $order_data['data']['total'];
                $result['all_page'] = ceil($order_data['data']['total'] / 100);

                //更新数据
                if (!empty($order_data['data']['list'])) {
                    $this->putOrder($order_data['data']['list'], $shop_name);
                }
            }

        }

        return $result;
    }

    /*
     * 订单入库
     */
    public function putOrder($data, $shop_name)
    {

        $put_data = [];
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                //子订单
                foreach ($v['child'] as $kk => $vv) {

                    $list = [];
                    $list['order_id'] = $vv['order_id'] ?? '';
                    $list['origin_prod_name'] = $vv['product_name'] ?? '';
                    $list['origin_prod_id'] = $vv['product_id'] ?? '';
                    //属性处理
//                    $spec_desc = array();
//                    foreach ($vv['spec_desc'] as $kkk => $vvv) {
//                        $spec_desc[$vvv['name']] = $vvv['value'] ?? '';
//                    }
//                    $spec_desc['额外'] = $vv['code'] ?? '';
//                    $list['code'] = $vv['code'] ?? '';
                    //$list['spec_desc'] = $spec_desc;
                    $list['create_time'] = !empty($vv['create_time']) ? $vv['create_time'] : NULL;
                    $list['combo_num'] = $vv['combo_num'] ?? 0;//该子订单所购买的sku的数量
                    $list['combo_amount'] = $vv['combo_amount'] / 100 ?? 0;//该子订单所购买的sku的售价
                    $list['post_receiver'] = $vv['post_receiver'] ?? '';
                    $list['post_tel'] = $vv['post_tel'] ?? '';
                    $list['shop_id'] = $vv['shop_id'] ?? '';
                    $list['shop_name'] = $shop_name;//店铺名称
                    $list['province'] = $vv['post_addr']['province']['name'] ?? '';
                    $list['city'] = $vv['post_addr']['city']['name'] ?? '';
                    $list['town'] = $vv['post_addr']['town']['name'] ?? '';
                    $list['detail'] = $vv['post_addr']['detail'] ?? '';
                    $list['order_status'] = $vv['order_status'] ?? -1;
                    $list['seller_words'] = $vv['seller_words'] ?? '';
                    $list['buyer_words'] = $vv['buyer_words'] ?? '';
                    $list['pid'] = $v['order_id'] ?? '';
                    $list['logistics_code'] = $vv['logistics_code'] ?? '';//物流单号
                    $list['coupon_amount'] = $v['coupon_amount'] / 100 ?? 0;//平台优惠券
                    $list['shop_coupon_amount'] = $v['shop_coupon_amount'] / 100 ?? 0;//商家优惠券
                    //金额说明
                    $pay_fee = $vv['total_amount'] / 100 ?? 0;//实付
                    $combo_fee = $vv['combo_amount'] / 100 * $vv['combo_num'] ?? 0;//商品金额
                    $coupon_fee = $vv['coupon_amount'] / 100 ?? 0;//优惠
                    $post_fee = $vv['post_amount'] / 100 ?? 0;//运费

                    $str = '用户实付：￥' . $pay_fee . ' 商品总额：￥' . $combo_fee . ' 运费：￥' . $post_fee . ' 优惠：￥' . $coupon_fee;
                    $list['amount_spec'] = $str;
                    $list['total_amount'] = $vv['total_amount'] / 100 ?? 0;//付款
                    array_push($put_data, $list);
                }

            }
//
            $url = 'http://dd.youdnr.com/api/order/store';


            $result = $this->fxgService->send_post($url, array("data" => json_encode($put_data)));

            return $put_data;


        }

    }


    /*
     * 订单备货数据比较Api
     */

    public function orderStatistic(Request $request)
    {
        set_time_limit(0);
        $start_time = $request->input('start_time') ?? date("Y-m-d", strtotime("-2 day")) . ' 00:00:00';
        $end_time = $request->input('end_time') ?? date("Y-m-d H:i:s");
        $shop = $this->getShop();

        $arr = [];
        foreach ($shop as $k => $v) {
            if (!empty($v['appKey']) && !empty($v['appSecret']) && !empty($v['shop_id'])) {
                //api 统计
                $attributes['APP_KEY'] = $v['appKey'];
                $attributes['APP_SECRET'] = $v['appSecret'];
                $attributes['timestamp'] = $end_time;
                $attributes['c'] = 'order';
                $attributes['a'] = 'list';
                $attributes['param_arr'] = array(
                    "start_time" => $start_time,
                    "end_time" => $end_time,
                    "is_desc" => '1',
                    "size" => "100",
                    "page" => "0",
                    'order_status' => '2'
                );


                $order_data = $this->fxgService->sendFxgRequest($attributes);

                //系统统计
                $data = DB::table('admin_orders')->select('order_status', 'order_id')->where('order_status', 2)->where('shop_id', $v['shop_id'])->whereBetween('create_time', [$start_time, $end_time])->count();


                $arr[$k]['shop_name'] = $v['shop_name'] ?? '';
                $arr[$k]['api_count'] = $order_data['data']['total'];
                $arr[$k]['system_count'] = $data;
            }
        }

        return $arr;
    }


    public function getShop()
    {
        //店铺信息
        $shops = file_get_contents('https://order.youdnr.com/api/temai/order/fxg_shop_list');
        $shop = json_decode($shops, true);
        $shop = !empty($shop['result']) ? $shop['result'] : [];

        return $shop;
    }



    /*钉钉通知退款订单*/

    public function orderDing(){

        $start_time =   date("Y-m-d", strtotime("-15 day")).' 06:00:00';
        $end_time   =   date("Y-m-d H:i:s");
        $result = '';
        $data    =    Order::where('order_status',16)->where('local_order_status',0)->whereBetween('create_time',[$start_time,$end_time])->get()->toArray();
        if(count($data) > 0){
            $token = '907333c555896d5e87913074a545b53c4c6a90032b186fff38774bcbf39fa674';
            $liver = new \App\Lib\DingDingNotice\Order($data,$token,$atMobiles = [],$isAtall = false);
            $result = $liver->sendMarkdownMessage();

        }

        return $result;

    }

    /*开普勒-回调地址*/
    public function writeUrl(Request $request)
    {
        $all    =   $request->all();

        //base_path()获取当前的绝对路径
        $path=base_path().'\public\text.txt';

        file_put_contents($path,$all);//把字符串内容存储
    }

    /*开普勒-商品列表*/
    public function goodsList(Request $request)
    {
        $all    =   $request->all();
        $url    =   "https://api.jd.com/routerjson?";
        $attributes['app_key'] = "653A5E8209148E4CB8DCF955091C655C";
        $attributes['method'] = "jingdong.ctp.ware.sku.getSkuList";
        $attributes['timestamp'] = date("Y-m-d H:i:s");
        $attributes['access_token'] = $this->access_token();
        $attributes['v'] = '2.0';
        $ctpProtocol    =   array(
            "customerId"=>125033640,
            "channelId"=>168703610,
            "opName"=>"wgss",
            "appKey"=>"653A5E8209148E4CB8DCF955091C655C"
        );
        $apiSkuListParam    =   array(
            "pageSize"=>100
        );
        $attributes['360buy_param_json'] =  array(
            "ctpProtocol"=>$ctpProtocol,
            "apiSkuListParam"=>$apiSkuListParam
        );
        $attributes['360buy_param_json']    =   json_encode($attributes['360buy_param_json']);

        //签名算法
        ksort($attributes);
        $attributes['sign'] = $this->createSign($attributes);

        $res = $this->https_request($url,$attributes);

        return $res;
    }

    /*
     * 签名生成
     * */
    public function createSign($attributes)
    {
        //$APP_KEY         =   "653A5E8209148E4CB8DCF955091C655C";
        $APP_SECRET         =   "db2d855b195f42f39c630327f871540e";

        $str = "360buy_param_json" . $attributes['360buy_param_json'] . "access_token" . $attributes['access_token'] . "app_key" . $attributes['app_key'] . "method" . $attributes['method']. "timestamp" . $attributes['timestamp'] . "v" . $attributes['v'];
        $md5_str = $APP_SECRET . $str . $APP_SECRET;
        $sign = md5($md5_str);
        //转大写
        $sign = strtoupper($sign);
        return $sign;
    }

    /*
     * 校验access_token
     * */
    public function access_token()
    {
        $access_token   =   Cache::get('access_token');
        if(!$access_token){
            $data['app_key']        =   "653A5E8209148E4CB8DCF955091C655C";
            $data['app_secret']     =   "db2d855b195f42f39c630327f871540e";
            $data['grant_type']     =   "authorization_code";
            $data['code']           =   "e7TVhk";
            $url    =   "https://open-oauth.jd.com/oauth2/access_token?";
            $res = $this->https_request($url,$data);
            $jsoninfo = json_decode($res, true);
            $access_token   =   $jsoninfo['access_token'] ?? '';
            Cache::put('access_token', $access_token, 1200);//minutes
        }
        return $access_token;
    }

    /**
     * 发送请求
     * @param $url：地址
     * @param null $data：post的数据
     * @return mixed：请求返回的结果
     */
    public static function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

}